package net.hn.hnms.biz.steelyard.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.collect.Lists;
import net.hn.hnms.biz.steelyard.domain.SteelyardHis;
import net.hn.hnms.biz.steelyard.enums.SteelyardEnum;
import net.hn.hnms.biz.steelyard.mapper.SteelyardHisMapper;
import net.hn.hnms.biz.steelyard.mapper.SteelyardNowMapper;
import net.hn.hnms.biz.steelyard.request.SteelyardHistoryReq;
import net.hn.hnms.biz.steelyard.service.ISteelyardService;
import net.hn.hnms.biz.steelyard.vo.SteelyardHistoryVO;
import net.hn.hnms.biz.steelyard.vo.SteelyardNowVO;
import net.hn.hnms.biz.steelyard.vo.SteelyardStatisticsVO;
import net.hn.hnms.sys.common.core.domain.ResponsePage;
import net.hn.hnms.sys.common.core.utils.DateUtils;
import net.hn.hnms.sys.common.mybatis.core.page.PageQuery;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author ly
 * 发运流水表服务层实现
 * @date 2022-08-30
 */

@Service
public class SteelyardServiceImpl implements ISteelyardService {

    @Autowired
    private SteelyardNowMapper steelyardNowMapper;

    @Autowired
    private SteelyardHisMapper steelyardHisMapper;

    /**
     * 实时数据
     */
    @Override
    public ResponsePage<SteelyardNowVO> now(PageQuery pageQuery, String mineCode) {
       /* Page<SteelyardNowVO> page = steelyardNowMapper.nowPageList(pageQuery.build(),new Date(),mineCode);
        List<SteelyardNowVO> steelyards = page.getRecords();
        if (CollUtil.isNotEmpty(steelyards)) {
            Set<String> deviceCodeSet = steelyards.stream().map(SteelyardNowVO::getDeviceCode).collect(Collectors.toSet());
            Set<String> dataTimeSet = steelyards.stream().map(SteelyardNowVO::getDataTime).collect(Collectors.toSet());

            List<SteelyardNow> steelyardsList = steelyardNowMapper.nowPageValue(deviceCodeSet, dataTimeSet,mineCode);

            for (SteelyardNowVO vo : steelyards) {
                List<SteelyardNow> list = steelyardsList.stream()
                        .filter(o -> o.getDeviceCode().equals(vo.getDeviceCode())
                                && DateUtil.format(o.getDataTime(), "yyyy-MM-dd").equals(vo.getDataTime())).collect(Collectors.toList());
                Map<String, Double> steelyardMapList = CollUtil.toMap(list, new HashMap<>(), SteelyardNow::getDataType, SteelyardNow::getDataValue);
                vo.setUa(steelyardMapList.getOrDefault(SteelyardEnum.Ua.getCode(),0.0));
                vo.setDs(steelyardMapList.getOrDefault(SteelyardEnum.Ds.getCode(),0.0));
                vo.setVv(steelyardMapList.getOrDefault(SteelyardEnum.Vv.getCode(),0.0));
                vo.setFld(steelyardMapList.getOrDefault(SteelyardEnum.Fld.getCode(),0.0));
                vo.setFfw(steelyardMapList.getOrDefault(SteelyardEnum.Ffw.getCode(),0.0));
                vo.setC1(steelyardMapList.getOrDefault(SteelyardEnum.C1.getCode(),0.0));
            }
        }*/
        //修改查询实时数据sql
        Page<SteelyardNowVO> page = steelyardNowMapper.nowPageList2(pageQuery.build());
        List<SteelyardNowVO> steelyards = page.getRecords();
        return new ResponsePage(steelyards, page.getTotal());
    }

    /**
     * 实时数据链接
     */
    @Override
    public Double nowLink(String mineCode){
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        String date = simpleDateFormat.format(new Date());
        Double nowSum = steelyardNowMapper.nowLink(mineCode,date);
        if (nowSum==null){
            nowSum = 0d;
        }
        return nowSum;
    }

    public Double maxForYearLink(String mineCode){
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy");
        String date = simpleDateFormat.format(new Date())+"-01-01";
        Double max = steelyardNowMapper.maxForYearLink(mineCode,date);
        if (max==null){
            max = 0d;
        }
        return max;
    }

    /**
     * 历史数据
     */
    @Override
    public ResponsePage<SteelyardHistoryVO> history(SteelyardHistoryReq req, PageQuery pageQuery) {


        Page<SteelyardHistoryVO> historyVOPage = steelyardHisMapper.pageList(pageQuery.build(), req.getDeviceName(),new Date(), req.getBeginDate(), req.getEndDate(),req.getMineCode());
        List<SteelyardHistoryVO> historyVOList = historyVOPage.getRecords();
        if (CollUtil.isNotEmpty(historyVOList)) {
            Set<String> deviceCodeSet = historyVOList.stream().map(SteelyardHistoryVO::getDeviceCode).collect(Collectors.toSet());
            Set<String> dataTimeSet = historyVOList.stream().map(SteelyardHistoryVO::getTime).collect(Collectors.toSet());

            List<SteelyardHis> allHistoryPage = steelyardHisMapper.selectHistoryList(deviceCodeSet, dataTimeSet,req.getMineCode());

            for (SteelyardHistoryVO steelyardHistoryVO : historyVOList) {
                List<SteelyardHis> list = allHistoryPage.stream()
                        .filter(o -> o.getDeviceCode().equals(steelyardHistoryVO.getDeviceCode())
                                && DateUtil.format(o.getDataTime(), "yyyy-MM-dd").equals(steelyardHistoryVO.getTime())).collect(Collectors.toList());

                Map<String, Double> steelyardMapList = CollUtil.toMap(list, new HashMap<>(), k -> k.getDataType() + "-" + k.getCla(), SteelyardHis::getDataValue);

                steelyardHistoryVO.setMorningShift(steelyardMapList.getOrDefault(StrUtil.join("-", SteelyardEnum.C1.getCode(), "1"), 0.0));
                steelyardHistoryVO.setNoonShift(steelyardMapList.getOrDefault(StrUtil.join("-", SteelyardEnum.C1.getCode(), "2"), 0.0));
                steelyardHistoryVO.setEveningShift(steelyardMapList.getOrDefault(StrUtil.join("-", SteelyardEnum.C1.getCode(), "3"), 0.0));

                steelyardHistoryVO.setDs(getDayAndMonthAndYear(steelyardMapList,SteelyardEnum.Ds));
                steelyardHistoryVO.setMs(getDayAndMonthAndYear(steelyardMapList,SteelyardEnum.Ms));
                steelyardHistoryVO.setYs(getDayAndMonthAndYear(steelyardMapList,SteelyardEnum.Ys));
            }
        }

        return new ResponsePage<>(historyVOList, historyVOPage.getTotal());
    }

    private Double getDayAndMonthAndYear(Map<String, Double> steelyardMapList, SteelyardEnum steelyardEnum) {
        Double value = steelyardMapList.getOrDefault(StrUtil.join("-", steelyardEnum.getCode(), "3"), 0.0);
        if(value == 0.0){
            value = steelyardMapList.getOrDefault(StrUtil.join("-", steelyardEnum.getCode(), "2"), 0.0);
            if(value == 0.0){
                value = steelyardMapList.getOrDefault(StrUtil.join("-", steelyardEnum.getCode(), "1"), 0.0);
            }
        }
        return value;
    }

    /**
     * 饼图 统计分析
     */
    @Override
    public List<SteelyardStatisticsVO> pieChart(Date dateTime, String mineCode) {
        List<SteelyardHistoryVO> devices = steelyardHisMapper.selectDeviceList(mineCode);
        Map<String, Double> newsMap = steelyardHisMapper.selectYearNewList(dateTime == null ? new Date() : dateTime,mineCode)
                .stream().collect(Collectors.toMap(SteelyardStatisticsVO::getName, SteelyardStatisticsVO::getValue));

        List<SteelyardStatisticsVO> results = new ArrayList<>();
        for (SteelyardHistoryVO device : devices) {
            SteelyardStatisticsVO vo = new SteelyardStatisticsVO();
            vo.setName(device.getDeviceName());
            vo.setValue(newsMap.getOrDefault(device.getDeviceName(), 0D));
            results.add(vo);
        }
        return results;
    }

    /**
     * 柱状图 统计分析
     */
    @Override
    public List<SteelyardStatisticsVO> columnChart(Date dateTime,String mineCode) {

        List<SteelyardStatisticsVO> results = new ArrayList<>();

        Map<String, Double> resultMap = steelyardHisMapper.selectMonthNewList(dateTime,mineCode)
                .stream().collect(Collectors.toMap(SteelyardStatisticsVO::getName, SteelyardStatisticsVO::getValue));

        Date[] dateRange = DateUtils.getDateRangeUtilNow(DateUtil.year(new Date()), dateTime == null ? null : DateUtil.month(dateTime) + 1);
        Date startDate = dateRange[0];
        Date endDate = dateRange[1];
        long months = DateUtil.betweenMonth(startDate, endDate, false);
        for (int i = 0; i <= months; i++) {
            Date offset = DateUtil.offsetMonth(startDate, i);
            SteelyardStatisticsVO vo = new SteelyardStatisticsVO();
            String key = DateUtil.format(offset, "yyyy-MM");
            vo.setName(DateUtil.format(offset, months > 5 ? "MM" : "yyyy-MM"));
            vo.setValue(resultMap.getOrDefault(key, 0D));
            results.add(vo);
            if (DateUtil.isSameMonth(offset, endDate)) {
                break;
            }
        }
        return Lists.reverse(results);
    }
}
